package com.xiaotu.easypoi.verify;

import cn.afterturn.easypoi.excel.annotation.ExcelEntity;
import cn.afterturn.easypoi.excel.entity.result.ExcelVerifyHandlerResult;
import cn.afterturn.easypoi.handler.inter.IExcelVerifyHandler;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ArrayUtil;
import com.xiaotu.easypoi.testimport.model.ImportUserModel;
import lombok.SneakyThrows;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;


/**
 * @author Mr.zhang
 * @module easypoi-demo
 * @date 2022-05-31 18:45
 */
@Component
public class ImportExcelVerifyHandler implements IExcelVerifyHandler<ImportUserModel> {

    private ThreadLocal<List<Boolean>> threadLocal = new ThreadLocal<>();

    @SneakyThrows
    @Override
    public ExcelVerifyHandlerResult verifyHandler(ImportUserModel bean) {
        threadLocal.set(null);
        verifyAllField(bean);
        List<Boolean> collect = threadLocal.get().stream().filter(b -> b.booleanValue() == true).collect(Collectors.toList());
        return new ExcelVerifyHandlerResult(CollUtil.isNotEmpty(collect));
    }

    private void verifyAllField(Object bean) throws IllegalAccessException {
        List<String> ignoreFiledNames = new ArrayList<>();
        //获取包含@ExcelEntity的嵌套对象
        Field[] declaredFields = bean.getClass().getDeclaredFields();
        for (Field field : declaredFields) {
            boolean annotationPresent = field.isAnnotationPresent(ExcelEntity.class);
            if (annotationPresent) {
                field.setAccessible(true);
                ignoreFiledNames.add(field.getName());
                verifyAllField(field.get(bean));
            }
        }
        boolean notEmpty = BeanUtil.isNotEmpty(bean, ArrayUtil.toArray(ignoreFiledNames, String.class));
        if (CollUtil.isEmpty(threadLocal.get())) {
            List<Boolean> booleanList = new ArrayList<>();
            booleanList.add(notEmpty);
            threadLocal.set(booleanList);
        } else {
            threadLocal.get().add(notEmpty);
        }
    }

}
